<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Prize as PrizeModel;
use app\admin\model\User;
use app\admin\model\PrizeUser;
use app\admin\model\Category;
use think\Db;
use think\Exception;

/**
 * 产品管理
 *
 * @icon   fa fa-list
 */
class Prize extends Backend
{

    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new PrizeModel();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                //判断是否已经开奖?
                $v['user_num'] = PrizeUser::where(['prize_id'=>$v['id']])->count();
                
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 指定中奖用户
     *
     * @return string
     * @throws \think\Exception
     */
    public function prize_user($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if($row['start_time']){
                $row['start_time'] = date('Y-m-d H:i:s',$row['start_time']);
            }
            if($row['start_time']){
                $row['prize_time'] = date('Y-m-d H:i:s',$row['prize_time']);
            }
            $this->view->assign('row', $row);

            $user_list =  PrizeUser::alias('a')
					->field("a.*,b.avatar,b.nickname")
					->join("user b","b.id = a.user_id")
					->where(['prize_id'=>$ids])
					->select();
            $this->view->assign('user_list', $user_list);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $params['one_award_user_list'] = implode(',',$params['one_award_user_list']);
            $params['tow_award_user_list'] = implode(',',$params['tow_award_user_list']);
            $params['three_award_user_list'] = implode(',',$params['three_award_user_list']);
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }

   /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            if(!empty($params['start_time'])){
                $params['start_time'] = strtotime($params['start_time']);
            }
            if(!empty($params['prize_time'])){
                $params['prize_time'] = strtotime($params['prize_time']);
            }
            $params['add_time'] = time();
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


     /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if($row['start_time']){
                $row['start_time'] = date('Y-m-d H:i:s',$row['start_time']);
            }
            if($row['prize_time']){
                $row['prize_time'] = date('Y-m-d H:i:s',$row['prize_time']);
            }
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            if(!empty($params['start_time'])){
                $params['start_time'] = strtotime($params['start_time']);
            }
            if(!empty($params['prize_time'])){
                $params['prize_time'] = strtotime($params['prize_time']);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}